package com.kgc.controller;

import com.github.pagehelper.PageInfo;
import com.kgc.pojo.Product;
import com.kgc.pojo.Sale;
import com.kgc.pojo.User;
import com.kgc.service.ProductService;
import com.kgc.service.SaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("/sale")
public class SaleController {
    @Autowired
    private SaleService saleService;
    @Autowired
    private ProductService productService;
    @RequestMapping("/add")
    public String addSale(Integer productId, Double price, Integer quantity, HttpSession session, Model model) throws IllegalAccessException {
        User user=(User)session.getAttribute("user");
        if(user==null){
            model.addAttribute("error","请登录后再操作！");
            return "forward:/jsp/index.jsp";

        }
        Product product=productService.selectProductById(productId);
        if(product.getQuantity()<quantity){
            model.addAttribute("error","该商品库存不足，请修改数量后重新添加！");
            return "forward:/jsp/main.jsp";
        }

        product.setQuantity(product.getQuantity()-quantity);

        Sale sale=new Sale(price,quantity,price*quantity,new Date(),user.getId(),productId);
        //product.setId(null);
        Integer row=saleService.addSale(sale,product);

        if(row<2){
            model.addAttribute("error","添加失败！");
            return "forward:/jsp/main.jsp";

        }
        return "redirect:/jsp/main.jsp";
    }

    @RequestMapping("/list")
    @ResponseBody
    public PageInfo<Sale> selectSaleList(String order,Integer pageNo){
        Integer pageSize=5;
        return saleService.selectSaleList(order,pageNo,pageSize);
    }
}
